import { instance } from "./api.interceptor";

export const AuthService = {


    async refreshTokens() {
        try {
            const resp = await instance.get<{ accessToken: string }>('auth/refresh-tokens')
            return resp.data.accessToken
        } catch (e) {
            console.log(e)
        }
    },

    async login(
        loginBodyDto: { email: string, password: string },
    ) {
        try {
            const resp = await instance.post<{ accessToken: string }>(
                '/auth/login',
                loginBodyDto
            )
            localStorage.setItem('token', resp.data.accessToken)
            localStorage.setItem('isAuth', 'true')
            return resp;
        } catch (error) {
            throw error
        }

    },
    async register(
        registerBodyDto: { email: string, password: string },
    ) {
        try {
            const resp = await instance.post<{ accessToken: string }>(
                '/auth/register',
                registerBodyDto
            )
            try {
                const resp = await instance.post<{ accessToken: string }>(
                    '/auth/login',
                    registerBodyDto
                )
                localStorage.setItem('token', resp.data.accessToken)
                localStorage.setItem('isAuth', 'true')
                return resp;
            } catch (error) {
                throw error
            }
        } catch (error) {
            throw error
        }
    },
    async logout() {
        try {
            const resp = await instance.get<void>(
                '/auth/logout'
            )
            localStorage.removeItem('isAuth')
            localStorage.removeItem('token')
            return resp;
        } catch (error) {
            throw error
        }
    }
}

